package org.melanesia.converters.java;

import java.io.Reader;
import java.sql.Clob;

import org.melanesia.converters.JavaToJavaConverter;
import org.melanesia.exceptions.ConversionException;


/**
 * Converts Clob to a String representing this clob's content.
 *  
 * @author mkielar
 */
public class ClobToStringConverter implements JavaToJavaConverter {

	@Override
	public Object convert(Object value) throws ConversionException {
		try {
			Clob clob = (Clob)value;
			
			if (clob == null) return null;
	        Reader reader = clob.getCharacterStream();
	        
	        char[] buffer = new char[1024];
	        StringBuilder sb = new StringBuilder();
	        
	        while (true) 
	        {
	            int cnt = reader.read(buffer);
	            if (cnt < 0) break;
	            sb.append(buffer, 0, cnt);
	        }
	        
	        return sb.toString();
		} catch (Throwable t) {
			throw new ConversionException(t.getMessage(), t);
		}
	}
};
